<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>房主功能测试</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
        }

        .test-section {
            background: rgba(255, 255, 255, 0.1);
            margin: 20px 0;
            padding: 20px;
            border-radius: 10px;
            backdrop-filter: blur(10px);
        }

        button {
            background: #4CAF50;
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 5px;
            cursor: pointer;
            margin: 5px;
        }

        button:hover {
            background: #45a049;
        }

        button:disabled {
            background: #666;
            cursor: not-allowed;
        }

        .log {
            background: rgba(0, 0, 0, 0.3);
            padding: 10px;
            border-radius: 5px;
            height: 400px;
            overflow-y: auto;
            font-family: monospace;
            font-size: 12px;
        }

        .input-group {
            margin: 10px 0;
        }

        .input-group label {
            display: block;
            margin-bottom: 5px;
        }

        .input-group input {
            width: 100%;
            padding: 8px;
            border: none;
            border-radius: 4px;
            margin-bottom: 10px;
        }

        .success {
            color: #4CAF50;
        }

        .error {
            color: #f44336;
        }

        .info {
            color: #2196F3;
        }

        .warning {
            color: #ff9800;
        }

        .debug {
            color: #9c27b0;
        }

        .grid {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 20px;
        }

        .status {
            padding: 10px;
            border-radius: 5px;
            margin: 10px 0;
        }

        .connected {
            background: rgba(76, 175, 80, 0.3);
            border: 1px solid #4CAF50;
        }

        .disconnected {
            background: rgba(244, 67, 54, 0.3);
            border: 1px solid #f44336;
        }

        .host-badge {
            background: #ff9800;
            color: white;
            padding: 2px 6px;
            border-radius: 3px;
            font-size: 10px;
            margin-left: 5px;
        }

        .players-list {
            background: rgba(255, 255, 255, 0.1);
            padding: 10px;
            border-radius: 5px;
            margin: 10px 0;
        }

        .player-item {
            display: flex;
            align-items: center;
            padding: 5px;
            margin: 5px 0;
            background: rgba(255, 255, 255, 0.1);
            border-radius: 5px;
        }

        .player-item.current {
            background: rgba(76, 175, 80, 0.3);
            border: 1px solid #4CAF50;
        }

        .player-item.host {
            background: rgba(255, 152, 0, 0.3);
            border: 1px solid #ff9800;
        }
    </style>
</head>

<body>
    <h1>👑 房主功能测试</h1>

    <div class="test-section">
        <h2>🔧 房主功能说明</h2>
        <ul>
            <li>✅ 第一个加入房间的玩家自动成为房主</li>
            <li>✅ 房主信息持久化到数据库</li>
            <li>✅ 页面刷新后正确识别房主身份</li>
            <li>✅ 只有房主可以开始游戏</li>
            <li>✅ 房主离开后房主权限自动转移</li>
        </ul>
    </div>

    <div class="grid">
        <div class="test-section">
            <h2>🔌 连接测试</h2>
            <div class="input-group">
                <label>房间码:</label>
                <input type="text" id="roomCode" value="HOSTTEST" />
            </div>
            <div class="input-group">
                <label>玩家昵称:</label>
                <input type="text" id="playerName" value="房主测试" />
            </div>
            <button onclick="testConnection()">连接并加入房间</button>
            <button onclick="disconnect()">断开连接</button>
            <div id="connectionStatus" class="status disconnected">未连接</div>
        </div>

        <div class="test-section">
            <h2>🎮 房主功能测试</h2>
            <button onclick="testReadyFunction()" id="readyBtn" disabled>测试准备功能</button>
            <button onclick="testStartGame()" id="startBtn" disabled>测试开始游戏（仅房主）</button>
            <button onclick="testRefreshPage()" id="refreshBtn" disabled>模拟页面刷新</button>
            <div id="gameStatus" class="status">未加入房间</div>
            <div id="hostStatus" class="status">未识别房主</div>
        </div>
    </div>

    <div class="test-section">
        <h2>👥 玩家列表</h2>
        <div id="playersList" class="players-list">
            <p>暂无玩家</p>
        </div>
    </div>

    <div class="test-section">
        <h2>📊 状态信息</h2>
        <div id="statusInfo"></div>
    </div>

    <div class="test-section">
        <h2>📝 实时日志</h2>
        <div id="log" class="log"></div>
        <button onclick="clearLog()">清空日志</button>
    </div>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/microsoft-signalr/6.0.1/signalr.min.js"></script>
    <script>
        let connection = null;
        let currentRoomCode = null;
        let currentPlayerName = null;
        let currentPlayerId = null;
        let isConnected = false;
        let gameStatus = 'waiting';
        let players = [];
        let isHost = false;

        function log(message, type = 'info') {
            const logDiv = document.getElementById('log');
            const timestamp = new Date().toLocaleTimeString();
            const className = type;
            logDiv.innerHTML += `<div class="${className}">[${timestamp}] ${message}</div>`;
            logDiv.scrollTop = logDiv.scrollHeight;
        }

        function clearLog() {
            document.getElementById('log').innerHTML = '';
        }

        function updateConnectionStatus(connected) {
            const statusDiv = document.getElementById('connectionStatus');
            if (connected) {
                statusDiv.className = 'status connected';
                statusDiv.textContent = '已连接';
            } else {
                statusDiv.className = 'status disconnected';
                statusDiv.textContent = '未连接';
            }
            isConnected = connected;
        }

        function updateGameStatus(status) {
            document.getElementById('gameStatus').textContent = status;
            gameStatus = status;
        }

        function updateHostStatus() {
            const hostDiv = document.getElementById('hostStatus');
            if (isHost) {
                hostDiv.className = 'status connected';
                hostDiv.textContent = '✅ 你是房主';
            } else {
                hostDiv.className = 'status disconnected';
                hostDiv.textContent = '❌ 你不是房主';
            }
        }

        function updatePlayersList() {
            const playersDiv = document.getElementById('playersList');
            if (players.length === 0) {
                playersDiv.innerHTML = '<p>暂无玩家</p>';
                return;
            }

            playersDiv.innerHTML = players.map(player => {
                const isCurrentPlayer = (player.id || player.Id) === currentPlayerId;
                const isPlayerHost = player.isHost || player.IsHost;
                const playerClass = isCurrentPlayer ? 'current' : (isPlayerHost ? 'host' : '');

                return `
                    <div class="player-item ${playerClass}">
                        <div style="flex: 1;">
                            <strong>${player.nickName || player.NickName || '未知玩家'}</strong>
                            ${isPlayerHost ? '<span class="host-badge">房主</span>' : ''}
                            ${isCurrentPlayer ? '<span class="host-badge">我</span>' : ''}
                        </div>
                        <div>
                            ${(player.isReady || player.IsReady) ? '<span class="host-badge">已准备</span>' : ''}
                        </div>
                    </div>
                `;
            }).join('');
        }

        function updateStatusInfo() {
            const statusDiv = document.getElementById('statusInfo');
            statusDiv.innerHTML = `
                <h3>当前状态</h3>
                <p><strong>连接状态:</strong> ${isConnected ? '已连接' : '未连接'}</p>
                <p><strong>房间码:</strong> ${currentRoomCode || '未设置'}</p>
                <p><strong>玩家昵称:</strong> ${currentPlayerName || '未设置'}</p>
                <p><strong>玩家ID:</strong> ${currentPlayerId || '未设置'}</p>
                <p><strong>房主状态:</strong> ${isHost ? '是房主' : '不是房主'}</p>
                <p><strong>游戏状态:</strong> ${gameStatus}</p>
                <p><strong>玩家数量:</strong> ${players.length}</p>
                <p><strong>连接对象:</strong> ${connection ? '存在' : '不存在'}</p>
                <p><strong>连接状态:</strong> ${connection?.state || '未知'}</p>
            `;
        }

        function enableButtons() {
            document.getElementById('readyBtn').disabled = false;
            document.getElementById('startBtn').disabled = false;
            document.getElementById('refreshBtn').disabled = false;
        }

        async function testConnection() {
            try {
                const url = 'http://localhost:5152/gamehub';
                log(`正在连接SignalR: ${url}`, 'info');

                connection = new signalR.HubConnectionBuilder()
                    .withUrl(url)
                    .withAutomaticReconnect([0, 2000, 10000, 30000])
                    .build();

                // 设置事件处理器
                connection.on('PlayerJoined', (player) => {
                    log(`玩家加入: ${player.nickName || player.NickName}`, 'success');
                    updatePlayersFromServer();
                });

                connection.on('PlayerLeft', (playerId) => {
                    log(`玩家离开: ${playerId}`, 'warning');
                    updatePlayersFromServer();
                });

                connection.on('PlayerReady', (playerId, ready) => {
                    log(`玩家准备状态: ${playerId} = ${ready}`, 'info');
                    updatePlayersFromServer();
                });

                connection.on('GameStarted', (gameData) => {
                    log(`游戏开始: ${JSON.stringify(gameData)}`, 'success');
                    updateGameStatus('playing');
                });

                connection.on('HostChanged', (newHostId, newHostName) => {
                    log(`房主变更: ${newHostName} (${newHostId})`, 'warning');
                    updatePlayersFromServer();
                });

                connection.on('Error', (error) => {
                    log(`错误: ${error}`, 'error');
                });

                await connection.start();
                updateConnectionStatus(true);
                log('SignalR连接成功', 'success');

                // 加入房间
                currentRoomCode = document.getElementById('roomCode').value;
                currentPlayerName = document.getElementById('playerName').value;

                log(`加入房间: ${currentRoomCode}, 玩家: ${currentPlayerName}`, 'info');
                await connection.invoke('JoinGame', currentRoomCode, currentPlayerName, null);
                updateGameStatus('已加入房间');
                log('成功加入房间', 'success');

                // 获取房间信息
                await updatePlayersFromServer();

                enableButtons();
                updateStatusInfo();
            } catch (error) {
                log(`连接失败: ${error.message}`, 'error');
                updateConnectionStatus(false);
            }
        }

        async function updatePlayersFromServer() {
            try {
                const response = await fetch(`http://localhost:5152/api/games/${currentRoomCode}`);
                if (response.ok) {
                    const gameData = await response.json();
                    players = gameData.players || gameData.Players || [];

                    // 找到当前玩家
                    const currentPlayer = players.find(p =>
                        (p.nickName || p.NickName) === currentPlayerName
                    );

                    if (currentPlayer) {
                        currentPlayerId = currentPlayer.id || currentPlayer.Id;
                        isHost = currentPlayer.isHost || currentPlayer.IsHost || false;
                        log(`当前玩家信息: ID=${currentPlayerId}, 房主=${isHost}`, 'info');
                    }

                    updatePlayersList();
                    updateHostStatus();
                    updateStatusInfo();
                }
            } catch (error) {
                log(`获取房间信息失败: ${error.message}`, 'error');
            }
        }

        async function disconnect() {
            if (connection) {
                try {
                    await connection.stop();
                    connection = null;
                    updateConnectionStatus(false);
                    updateGameStatus('已断开连接');
                    log('已断开连接', 'info');

                    // 禁用按钮
                    document.getElementById('readyBtn').disabled = true;
                    document.getElementById('startBtn').disabled = true;
                    document.getElementById('refreshBtn').disabled = true;
                } catch (error) {
                    log(`断开连接失败: ${error.message}`, 'error');
                }
            }
        }

        async function testReadyFunction() {
            if (!isConnected) {
                log('未连接到服务器', 'error');
                return;
            }

            try {
                log('测试准备功能...', 'info');
                await connection.invoke('SetReady', currentRoomCode, currentPlayerName, true);
                log('✅ 准备功能测试成功', 'success');
                await updatePlayersFromServer();
            } catch (error) {
                log(`❌ 准备功能测试失败: ${error.message}`, 'error');
            }
        }

        async function testStartGame() {
            if (!isConnected) {
                log('未连接到服务器', 'error');
                return;
            }

            if (!isHost) {
                log('❌ 只有房主可以开始游戏', 'error');
                return;
            }

            try {
                log('测试开始游戏...', 'info');
                await connection.invoke('StartGame', currentRoomCode, currentPlayerId || currentPlayerName);
                log('✅ 开始游戏测试成功', 'success');
            } catch (error) {
                log(`❌ 开始游戏测试失败: ${error.message}`, 'error');
            }
        }

        async function testRefreshPage() {
            log('模拟页面刷新...', 'info');

            // 保存当前状态到localStorage
            localStorage.setItem(`player_${currentRoomCode}`, JSON.stringify({
                id: currentPlayerId,
                nickName: currentPlayerName,
                isHost: isHost
            }));

            log('✅ 状态已保存到localStorage', 'success');
            log('现在可以刷新页面测试房主身份恢复', 'warning');
        }

        // 页面加载时初始化
        window.onload = function () {
            log('房主功能测试页面已加载', 'info');
            log('请确保后端服务在 http://localhost:5152 运行', 'warning');
            updateStatusInfo();
        };
    </script>
</body>

</html>